package com.server.dataSource;

import com.dao.dataSource.DataConnectorMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.github.pagehelper.PageInfo;
import com.model.po.ColumnToShow;
import com.model.po.DataConnector;
import com.model.po.Databases;
import com.model.pojo.RepCode;
import com.model.pojo.RepEntity;
import com.model.pojo.TestPage;
import com.model.vo.configVo.ColumnRenameInfo;
import com.model.vo.configVo.DatabasesInfo;
import com.server.chart.GetChartsDataUtilService;
import com.config.BasesSource.DynamicDataSource;
import com.config.BasesSource.DynamicDataSourceContextHolder;
import com.config.BasesSource.DynamicDataSourceRegister;
import com.util.ContextUtil;
import com.util.GetTokenData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class DataBasesService {
    @Autowired
    DataConnectorMapper dataConnectorMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private DynamicDataSourceRegister dataSourceRegister;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    @Autowired
    GetTokenData getTokenData;
    /*
   保存数据库连接
    */

    public RepEntity inputDatabases(DatabasesInfo databasesInfo){
        if (databasesInfo == null || "".equals(databasesInfo)){
            return new RepEntity(RepCode.Null);
        }
        Databases databases = new Databases();
        BeanUtils.copyProperties(databasesInfo, databases);
        String note = databases.getNote();
        if (note == null || "".equals(note)){
            note = "";
            databases.setNote(note);
        }
        dataConnectorMapper.inputDataBases(databases);
        int id = databases.getId();

        databasesInfo.setId(id);
        //添加数据源可切换
        addDataSource(databasesInfo);

        return new RepEntity(RepCode.success,id);
    }

    /*
   查看数据库配置列表
    */
    public RepEntity getListDatabases(TestPage testPage){
        List<Databases> databasesList = dataConnectorMapper.getDatabasesList(testPage.enablePaging());
        List<Databases> databases = new ArrayList<>();
        Iterator isList = databasesList.iterator();
        while (isList.hasNext()){
            Databases databases1 = (Databases) isList.next();
            databases1.setPassWord("");
            databases.add(databases1);
        }
        PageInfo<Databases> pageInfo = new PageInfo<>(databases);
        return new RepEntity(RepCode.success, pageInfo);
    }

    /*
    删除数据库配置
     */
    public RepEntity delDatabases(List<Integer> idList){
        System.out.println(idList);
        dataConnectorMapper.deleteDatabases(idList);
        return new RepEntity(RepCode.success);
    }

    /*
    修改数据库配置
     */
    public RepEntity updatabases(DatabasesInfo databasesInfo){
        Databases databases = new Databases();
        BeanUtils.copyProperties(databasesInfo, databases);
        System.out.println(databases);
        if (databases.getPassWord() == null || "".equals(databases.getPassWord())){
            databases.setPassWord(null);
        }
        dataConnectorMapper.updatabases(databases);
        DatabasesInfo databasesInfo1 = dataConnectorMapper.getDatabases(databasesInfo.getId());
        addDataSource(databasesInfo1);
        return new RepEntity(RepCode.success);
    }

    /*
    查询列数据
     */
    public RepEntity getColumnData(int id){
        DataConnector dataConnector = new DataConnector();
        dataConnector = dataConnectorMapper.getColumnData(id);
        if (dataConnector == null || "".equals(dataConnector)){
            return new RepEntity(RepCode.Null);
        }
        String columnData = dataConnector.getColumnConfig();

        List<ColumnRenameInfo> configList = new ArrayList<>();
        if (columnData != null || (!"".equals(columnData))){
            try {
                CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, ColumnRenameInfo.class);
                configList =  objectMapper.readValue(columnData, javaType);   //这里不需要强制转换
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        List<ColumnToShow> toShows = new ArrayList<>();


        for (int i = 0; i < configList.size(); i++ ){
            ColumnRenameInfo columnRenameInfo = new ColumnRenameInfo();
            ColumnToShow columnToShow = new ColumnToShow();
            columnRenameInfo = configList.get(i);
            if ("1".equals(columnRenameInfo.getIsOpen())) {
                columnToShow.setColumnName(columnRenameInfo.getColumnName());
                columnToShow.setColumnRaname(columnRenameInfo.getColumnLable());
                columnToShow.setColumnType(columnRenameInfo.getColumnType());
                columnToShow.setIsGroup(columnRenameInfo.getIsGroup());
                columnToShow.setIsSubsection(columnRenameInfo.getIsSubsection());
                toShows.add(columnToShow);
            }
        }
        return new RepEntity(RepCode.success,toShows);
    }

    /*
    查询列数据通过图表ID
     */
    public RepEntity getColumnByChartId(int id){
        DataConnector dataConnector = new DataConnector();
        int ConnectId = getChartsDataUtilService.getConnectId(id);
        System.out.println("baseId："+ConnectId);
        dataConnector = dataConnectorMapper.getColumnData(ConnectId);
        if (dataConnector == null || "".equals(dataConnector)){
            return new RepEntity(RepCode.Null);
        }
        String columnData = dataConnector.getColumnConfig();

        List<ColumnRenameInfo> configList = new ArrayList<>();
        if (columnData != null || (!"".equals(columnData))){
            try {
                CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, ColumnRenameInfo.class);
                configList =  objectMapper.readValue(columnData, javaType);   //这里不需要强制转换
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        List<ColumnToShow> toShows = new ArrayList<>();


        for (int i = 0; i < configList.size(); i++ ){
            ColumnRenameInfo columnRenameInfo = new ColumnRenameInfo();
            ColumnToShow columnToShow = new ColumnToShow();
            columnRenameInfo = configList.get(i);
            if ("1".equals(columnRenameInfo.getIsOpen())) {
                columnToShow.setColumnName(columnRenameInfo.getColumnName());
                columnToShow.setColumnRaname(columnRenameInfo.getColumnLable());
                columnToShow.setColumnType(columnRenameInfo.getColumnType());
                columnToShow.setIsGroup(columnRenameInfo.getIsGroup());
                columnToShow.setIsSubsection(columnRenameInfo.getIsSubsection());
                toShows.add(columnToShow);
            }
        }
        return new RepEntity(RepCode.success,toShows);
    }

    //添加数据源
    private void addDataSource(DatabasesInfo databasesInfo) {
        //额外的数据源
        Map<String, Object> dsMap = new HashMap<>();
        dsMap.put("driver", "oracle.jdbc.driver.OracleDriver");
        dsMap.put("url", "jdbc:oracle:thin:@" + databasesInfo.getAddrass() +":" + databasesInfo.getPort() + ":" + databasesInfo.getDataName());
        dsMap.put("username", databasesInfo.getUserName());
        dsMap.put("password", databasesInfo.getPassWord());
        Map<Object, Object> target = dataSourceRegister.getTargetDataSources();
        if (target.size() == 0) {
            target.putAll(dataSourceRegister.getSlaveDataSources());
        }
        target.put(databasesInfo.getId(), dataSourceRegister.buildDataSource(dsMap));
        DynamicDataSource datasource = (DynamicDataSource) ContextUtil.getBean("dataSource");
        datasource.setTargetDataSources(target);
        datasource.afterPropertiesSet();

        DynamicDataSourceContextHolder.dataSourceIds.add(String.valueOf(databasesInfo.getId()));
    }

}
